package vikaa.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;

public class ImageBuilder {//
	private Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
	private ExecutorService executorService = Executors.newFixedThreadPool(5);
	private final Handler handler = new Handler();
	public static final String CACHE_FILE_PATH = Environment.getExternalStorageDirectory() + "/vikaa/wowo/thumbnail";
	
	public void loadDrawable(final String imageUrl, final ImageCallback callback) {
		Drawable drawable = null;
		final String fileName =  MD5Util.getMD5String(imageUrl);
		if (imageCache.containsKey(fileName)) {
			SoftReference softReference = imageCache.get(fileName);
			drawable = (Drawable) softReference.get();
			if (drawable != null) {
				callback.imageLoaded(imageUrl,drawable);
				return;
			}
		}
		executorService.submit(new LoadTask(fileName,imageUrl,callback));
	}
	
	class LoadTask implements Runnable {
		/**
		 * file name
		 */
		String fileName;
		/**
		 * image url
		 */
		String imageUrl;
		/**
		 * drawable
		 */
		Drawable drawable = null;
		/**
		 * call back
		 */
		ImageCallback callback;
		public LoadTask(String fileName,String imageUrl,ImageCallback callback){
			this.fileName = fileName;
			this.imageUrl = imageUrl;
			this.callback = callback;
		}
		public void run() {
			try {
				File dir = new File( CACHE_FILE_PATH);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				File file = new File(dir, fileName);
				if (file.exists() && file.length() > 0) {
					drawable = readFromSdcard(file);
				} else {
					drawable = loadImageFromUrl(imageUrl);
				}
				
				imageCache.put(fileName, new SoftReference(drawable));

				handler.post(new Runnable() {
					public void run() {
						callback.imageLoaded(imageUrl,drawable);
					}
				});
				if(!file.exists()){
					saveImageFile(imageUrl, fileName);
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}

	private Drawable readFromSdcard(File file) {
		try {
			FileInputStream in = new FileInputStream(file);
			return Drawable.createFromStream(in, file.getName());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	protected Drawable loadImageFromUrl(String imageUrl) {
		try {
			Drawable drawable = null;
			Bitmap bitmap = ImageUtils.getBitmapByPath(imageUrl,  100);
			return ImageUtils.bitmapToDrawable(bitmap);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	private void saveImageFile(String imageUrl,String fileName){
		if(!Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
			return;
		}
		File dir = new File(CACHE_FILE_PATH);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(dir, fileName);
		Bitmap bitmap = ImageUtils.getBitmapByPath(imageUrl, 100);
		try {
			ImageUtils.saveImageToSD(CACHE_FILE_PATH+"/"+fileName+".jpg", bitmap, 100);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public interface ImageCallback {
		public void imageLoaded(String url,Drawable imageDrawable);
	}
}